<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Largezhou\Admin\Form\Form;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // 验证头像
        if ($this->get(Form::UPLOAD_FLAG)) {
            return [
                'avatar' => 'file|max:500',
            ];
        }

        $user = optional($this->route('user'));

        $rules = [
            'name'  => 'required|max:50',
            'email' => 'required|max:100|email|unique:users,email,'.$user->id,
        ];

        if (!$user->exists || $user->password != $this->get('password')) {
            $rules['password'] = 'required|between:6,20|confirmed';
        }

        return $rules;
    }

    public function attributes()
    {
        return [
            'name'   => '用户名',
            'avatar' => '头像',
        ];
    }
}
